<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" shadow="always">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            v-model="query.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchHandle"
            >
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="success" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <!-- :data="" 只需要渲染表单数据 -->
      <!-- el-table-column表示一列 -->
      <!-- prop需要渲染的key -->
      <!-- border竖线 -->
      <!-- stripe斑马纹 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column
          align="center"
          label="*"
          type="index"
        ></el-table-column>
        <el-table-column
          align="center"
          label="姓名"
          prop="username"
        ></el-table-column>
        <el-table-column
          align="center"
          label="邮箱"
          prop="email"
        ></el-table-column>
        <el-table-column
          align="center"
          label="电话"
          prop="mobile"
        ></el-table-column>
        <el-table-column
          align="center"
          label="角色"
          prop="role_name"
        ></el-table-column>
        <el-table-column align="center" label="状态">
          <!-- 作用域插槽实现数据绑定 -->
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作模块 -->
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              plain
              size="small"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              plain
              size="small"
              icon="el-icon-delete"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 权限按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                plain
                size="small"
                icon="el-icon-setting"
                @click="showSetRoleHandle(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <!-- size-change 页面显示条数发生改变时触发 -->
      <!-- current-change 页码发生改变时触发 -->
      <!-- current-page 当前页码 -->
      <!-- page-sizes每页显示条数选项 -->
      <!-- page-size每页显示条数 -->
      <!-- layout配置分页显示 -->
      <!-- total总条数 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户弹出层 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @click="resetForm"
    >
      <!-- 添加用户表单 -->
      <el-form
        ref="addForm"
        :model="addUserForm"
        :rules="addUserRules"
        label-width="80px"
        @close="clearAddForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button @click="addUser" type="primary">添 加</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户弹出层 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="clearEditForm"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="ruleForm"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹出层 -->
    <el-dialog
      title="设置角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
    >
      <div>
        <p>用户名: {{ roleInfo.username }}</p>
        <p>角色名: {{ roleInfo.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'User',
  data () {
    // 自定义校验
    const checkEmail = (rule, value, cb) => {
      const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('邮箱格式不正确'))
      }
    }
    const checkMobile = (rule, value, cb) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('手机号码格式不正确'))
      }
    }
    return {
      // 页码
      query: {
        query: '', // 查询关键字
        pagenum: 1, // 当前页码
        pagesize: 5 // 每页条数
      },
      userList: [],
      total: 0,
      // 绑定数据
      addDialogVisible: false,
      // 用户表单
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加校验
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '请输入正确密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editDialogVisible: false, // 编辑弹框显示
      editForm: {}, // 编辑数据
      // 编辑校验
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setRoleDialogVisible: false, // 权限弹框
      roleInfo: {}, // 角色信息

      rolesList: [], // 角色列表
      selectedRoleId: '', // 选择后的iD
      userId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 数据改变
    handleSizeChange (val) {
      // console.log(val)
      this.query.pagesize = val
      this.getUserList()
    },
    // 页码改变
    handleCurrentChange (val) {
      // console.log(val)
      this.query.pagenum = val
      this.getUserList()
    },
    // 用户数据列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.query
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 修改用户状态
    async userStateChanged (userinfo) {
      console.log(userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 搜索
    searchHandle () {
      this.getUserList()
    },
    // 重置添加表单
    resetForm () {
      this.$refs.addForm.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addForm.validate(async valid => {
        if (!valid) {
          return this.$message.error('请输入用户信息')
        }
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 显示编辑用户弹框
    async showEditDialog (userId) {
      // console.log(userId)
      const { data: res } = await this.$http.get(`users/${userId}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    clearAddForm () {
      this.$refs.addForm.resetFields()
    },
    clearEditForm () {
      this.$refs.ruleForm.resetFields()
    },
    toEdit () {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) {
          return this.$message.error('请检查用户信息')
        }
        const { data: res } = await this.$http.put(
          `users/${this.editForm.id}`,
          this.editForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 删除用户
    async deleteUser (userId) {
      const confirmRes = await this.$confirm(
        '是否删除用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }
      ).catch(err => err)
      // console.log(confirmRes)
      if (confirmRes === 'cancel') {
        return this.$message.error('已经取消删除操作')
      }
      const { data: res } = await this.$http.delete(`users/${userId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败!')
      }
      this.$message.success('删除用户成功!')
      if (this.total % this.query.pagesize === 1 && this.query.pagenum > 1) {
        this.query.pagenum--
      }
      this.getUserList()
    },
    // 显示权限
    async showSetRoleHandle (role) {
      // 请求数据
      this.roleInfo = role
      this.userId = role.id
      // 角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)

      this.rolesList = res.data

      this.setRoleDialogVisible = true
    },
    async setRole () {
      const { data: res } = await this.$http.put(`users/${this.userId}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getUserList()
      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>

</style>
